/**
 * 
 */
package vue.popup;

import java.awt.event.ActionEvent;

import javax.swing.JMenuItem;

import vue.session.IGSolverBlock;
import controller.ISessionManager;

/**
 * Pop up menu for {@link IGSolverBlock}.
 * 
 * @author GRONOWSKI Stephane svan001@aol.com
 * 
 *         igsat 2010
 * 
 */
public class JPopupSolver extends JPopupExecution {

	private static final long	serialVersionUID	= 1L;
	public static final String	TITLE_SOLUTION		= "SOLUTION_";


	public static final String	SOLUTION			= "Solver solution";

	private JMenuItem			solution;
	private IGSolverBlock		solver;

	/**
	 * Create a {@link JPopupSolver}.
	 * 
	 * @param solver
	 *            {@link IGSolverBlock} associate
	 * @param manager
	 *            the session manager
	 */
	public JPopupSolver(IGSolverBlock solver, ISessionManager manager) {
		super(null, manager);

		this.solver = solver;

		// createMenu();

		refresh();
	}

	@Override
	public void refresh() {
		super.refresh();

		if (solver.getSolver().getRes() == null)
		{// pas de res
			out.setEnabled(false);
			err.setEnabled(false);
			solution.setEnabled(false);
		}
		else
		{// result dispo
			if (solver.getSolver().getRes().getStdout() != null)
				out.setEnabled(true);
			else
				out.setEnabled(false);
			if (solver.getSolver().getRes().getStderr() != null)
				err.setEnabled(true);
			else
				err.setEnabled(false);
			if (solver.getSolver().getRes().getSolution() != null)
				solution.setEnabled(true);
			else
				solution.setEnabled(false);
		}
	}

	@Override
	protected void createMenu() {
		super.createMenu();
		addSeparator();

		// solver
		solution = new JMenuItem(SOLUTION);
		solution.addActionListener(this);

		add(solution);
	}

	@Override
	public void showStdout() {
		new IGOutFrame(TITLE_OUT + solver.getSolver().getDescritpion(), getStdout());
	}

	@Override
	public void showStderr() {
		new IGOutFrame(TITLE_ERR + solver.getSolver().getDescritpion(), getStderr());
	}

	/**
	 * Show the solution find by the solver.
	 */
	private void showSolution() {
		new IGOutFrame(TITLE_SOLUTION + solver.getSolver().getDescritpion(), solver.getSolver().getRes().getSolution());
	}

	@Override
	public void removeFromSession() {
		manager.removeExecution(solver.getSolver());
	}

	@Override
	public String getStderr() {
		return solver.getSolver().getRes().getStderr();
	}

	@Override
	public String getStdout() {
		return solver.getSolver().getRes().getStdout();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		super.actionPerformed(e);

		if (e.getSource() == solution)
		{// montre solution
			showSolution();
			return;
		}
	}
}
